// 发现页面专用JS

// 页面加载完成后执行
document.addEventListener('DOMContentLoaded', function() {
    // 初始化轮播图
    initSlider();
    
    // 初始化图片错误处理
    handleImageErrors();
    
    // 添加点击事件
    addClickEvents();
    
    // 初始化底部导航
    initTabBar();
    
    // 初始化下拉刷新
    initPullToRefresh();
    
    // 初始化搜索功能
    initSearch();
    
    // 初始化加载更多功能
    initLoadMore();
    
    // 初始化动画效果
    initAnimations();
});

// 轮播图功能
function initSlider() {
    const sliderContainer = document.querySelector('.slider-container');
    const indicators = document.querySelectorAll('.indicator');
    const sliderItems = document.querySelectorAll('.slider-item');
    
    if (!sliderContainer || !indicators.length || !sliderItems.length) return;
    
    let currentIndex = 0;
    let interval;
    const totalSlides = sliderItems.length;
    
    // 设置指示器点击事件
    indicators.forEach((indicator, index) => {
        indicator.addEventListener('click', () => {
            currentIndex = index;
            updateSlider();
            resetInterval();
        });
    });
    
    // 设置轮播图点击事件
    sliderItems.forEach((item, index) => {
        item.addEventListener('click', function() {
            // 获取当前轮播图的标题
            const title = this.querySelector('.slider-caption h3').textContent;
            const desc = this.querySelector('.slider-caption p').textContent;
            
            // 根据索引设置不同的跳转目标
            let targetPage = '';
            let targetId = index + 1; // 使用索引+1作为ID
            
            switch(index) {
                case 0:
                    targetPage = 'article-details.html';
                    break;
                case 1:
                    targetPage = 'resume-tips.html';
                    break;
                case 2:
                    targetPage = 'event-details.html';
                    break;
                default:
                    targetPage = 'article-details.html';
            }
            
            // 保存当前轮播图信息到localStorage（在详情页面可以读取）
            const bannerInfo = {
                title: title,
                description: desc,
                image: this.querySelector('img').src,
                id: targetId
            };
            
            localStorage.setItem('currentBanner', JSON.stringify(bannerInfo));
            
            // 跳转到相应页面
            window.location.href = `${targetPage}?id=${targetId}&source=banner`;
        });
    });
    
    // 更新轮播图显示
    function updateSlider() {
        // 移除所有active类
        sliderItems.forEach(item => {
            item.classList.remove('active');
        });
        
        // 为当前索引添加active类
        sliderItems[currentIndex].classList.add('active');
        
        // 更新指示器状态
        indicators.forEach((indicator, index) => {
            if (index === currentIndex) {
                indicator.classList.add('active');
            } else {
                indicator.classList.remove('active');
            }
        });
    }
    
    // 自动轮播
    function startAutoSlide() {
        interval = setInterval(() => {
            currentIndex = (currentIndex + 1) % totalSlides;
            updateSlider();
        }, 5000); // 每5秒切换一次
    }
    
    // 重置自动轮播计时器
    function resetInterval() {
        clearInterval(interval);
        startAutoSlide();
    }
    
    // 手指滑动支持
    let startX, moveX;
    let isDragging = false;
    
    sliderContainer.addEventListener('touchstart', (e) => {
        startX = e.touches[0].clientX;
        isDragging = true;
        clearInterval(interval);
    }, {passive: true});
    
    sliderContainer.addEventListener('touchmove', (e) => {
        if (!isDragging) return;
        moveX = e.touches[0].clientX;
    }, {passive: true});
    
    sliderContainer.addEventListener('touchend', () => {
        if (!isDragging) return;
        isDragging = false;
        
        const diff = moveX - startX;
        const threshold = sliderContainer.offsetWidth * 0.2; // 20%的阈值
        
        if (Math.abs(diff) >= threshold) {
            if (diff > 0 && currentIndex > 0) {
                // 向右滑动，显示上一张
                currentIndex--;
            } else if (diff < 0 && currentIndex < totalSlides - 1) {
                // 向左滑动，显示下一张
                currentIndex++;
            }
        }
        
        updateSlider();
        startAutoSlide();
    });
    
    // 初始化
    updateSlider();
    startAutoSlide();
}

// 图片错误处理
function handleImageErrors() {
    const images = document.querySelectorAll('img');

    images.forEach(img => {
        img.addEventListener('error', function() {
            let imageType = 'generic';
            
            // 根据图片所在容器类型设置不同的替代图
            if (this.closest('.slider-item')) {
                imageType = 'banner';
            } else if (this.closest('.article-img')) {
                imageType = 'article';
            } else if (this.closest('.event-item')) {
                imageType = 'event';
            } else if (this.closest('.tips-img')) {
                imageType = 'tips';
            } else if (this.closest('.access-icon')) {
                imageType = 'icon';
            } else if (this.closest('.assessment-icon')) {
                imageType = 'assessment';
            } else if (this.classList.contains('author-avatar')) {
                imageType = 'avatar';
            }
            
            // 生成随机ID以获取不同图片
            const randomId = Math.floor(Math.random() * 1000);
            
            // 根据图片类型设置替代图
            switch(imageType) {
                case 'banner':
                    this.src = `https://source.unsplash.com/random/800x400/?campus,university&sig=${randomId}`;
                    break;
                case 'article':
                    this.src = `https://source.unsplash.com/random/400x300/?career,business&sig=${randomId}`;
                    break;
                case 'event':
                    this.src = `https://source.unsplash.com/random/400x200/?event,seminar&sig=${randomId}`;
                    break;
                case 'tips':
                    this.src = `https://source.unsplash.com/random/400x300/?advice,career&sig=${randomId}`;
                    break;
                case 'assessment':
                    this.src = `https://source.unsplash.com/random/300x300/?test,career&sig=${randomId}`;
                    break;
                case 'avatar':
                    this.src = `https://i.pravatar.cc/150?img=${randomId % 70}`;
                    break;
                case 'icon':
                    // 为图标设置背景色而不是替代图
                    this.style.display = 'none';
                    const iconElement = this.closest('.access-icon');
                    if (iconElement) {
                        iconElement.innerHTML = '<i class="bi bi-star"></i>';
                    }
                    break;
                default:
                    this.src = `https://source.unsplash.com/random/300x200/?business&sig=${randomId}`;
            }
            
            // 设置加载模式为立即加载
            this.loading = 'eager';
            
            // 添加淡入效果
            this.style.opacity = '0';
            setTimeout(() => {
                this.style.transition = 'opacity 0.3s ease';
                this.style.opacity = '1';
            }, 50);
        });
    });
}

// 添加点击事件
function addClickEvents() {
    // 文章点击
    const articleItems = document.querySelectorAll('.article-item');
    articleItems.forEach(item => {
        item.addEventListener('click', function() {
            const title = this.querySelector('h3').textContent;
            console.log(`查看文章: ${title}`);
            // 跳转到文章详情页
            window.location.href = 'article-details.html';
        });
    });
    
    // 求职干货点击
    const tipsItems = document.querySelectorAll('.tips-item');
    tipsItems.forEach(item => {
        item.addEventListener('click', function() {
            const title = this.querySelector('h3').textContent;
            const id = this.getAttribute('data-id') || '1';
            console.log(`查看攻略: ${title}`);
            window.location.href = `tips-detail.html?id=${id}`;
        });
    });
}

// 初始化底部导航
function initTabBar() {
    const tabItems = document.querySelectorAll('.nav-item');
    tabItems.forEach(item => {
        item.addEventListener('click', function() {
            // 如果已经是活动状态的标签，则不做任何操作
            if (this.classList.contains('active')) return;
            
            // 移除所有标签的活动状态
            tabItems.forEach(tab => tab.classList.remove('active'));
            
            // 为当前点击的标签添加活动状态
            this.classList.add('active');
            
            // 获取目标页面
            const target = this.getAttribute('href');
            
            // 如果不是锚点链接，则跳转
            if (target && !target.startsWith('#')) {
                window.location.href = target;
            }
        });
    });
}

// 下拉刷新功能
function initPullToRefresh() {
    let startY;
    let diff;
    const threshold = 100; // 下拉触发的阈值
    const maxPull = 150; // 最大下拉距离
    const content = document.querySelector('.main-content');
    const header = document.querySelector('.header');
    
    // 添加下拉刷新指示器
    if (!document.querySelector('.refresh-indicator')) {
        const refreshIndicator = document.createElement('div');
        refreshIndicator.className = 'refresh-indicator';
        refreshIndicator.innerHTML = `
            <div class="refresh-icon">
                <i class="bi bi-arrow-clockwise"></i>
            </div>
            <div class="refresh-text">下拉刷新</div>
        `;
        content.insertBefore(refreshIndicator, content.firstChild);
    }
    
    const refreshIndicator = document.querySelector('.refresh-indicator');
    
    content.addEventListener('touchstart', (e) => {
        startY = e.touches[0].clientY;
        // 只有当页面滚动到顶部时才启用下拉刷新
        if (window.scrollY === 0) {
            content.style.transition = 'none';
        }
    }, {passive: true});
    
    content.addEventListener('touchmove', (e) => {
        // 只有当页面滚动到顶部时才处理下拉刷新
        if (window.scrollY > 0 || !startY) return;
        
        diff = e.touches[0].clientY - startY;
        
        // 只有下拉才有效
        if (diff <= 0) return;
        
        // 限制最大下拉距离
        if (diff > maxPull) diff = maxPull;
        
        // 使用缓动效果
        const pullDistance = Math.min(diff * 0.5, maxPull * 0.5);
        
        content.style.transform = `translateY(${pullDistance}px)`;
        
        // 更新刷新指示器文本
        if (pullDistance > threshold * 0.5) {
            refreshIndicator.classList.add('visible');
            refreshIndicator.querySelector('.refresh-text').innerText = pullDistance > threshold * 0.5 * 0.8 ? '释放刷新' : '下拉刷新';
        }
    }, {passive: true});
    
    content.addEventListener('touchend', () => {
        // 重置样式
        content.style.transition = 'transform 0.3s ease';
        
        if (diff && diff > threshold) {
            // 触发刷新
            refreshContent();
        } else {
            // 恢复原位
            content.style.transform = 'translateY(0)';
            refreshIndicator.classList.remove('visible');
        }
        
        // 重置变量
        startY = null;
        diff = 0;
    });
    
    function refreshContent() {
        // 显示刷新中状态
        refreshIndicator.classList.add('refreshing');
        refreshIndicator.querySelector('.refresh-text').innerText = '刷新中...';
        
        // 模拟加载过程
        setTimeout(() => {
            // 恢复原位并隐藏刷新指示器
            content.style.transform = 'translateY(0)';
            
            // 刷新内容
            updateBanners();
            updateArticles();
            
            // 完成刷新
            setTimeout(() => {
                refreshIndicator.classList.remove('refreshing');
                refreshIndicator.classList.remove('visible');
                showToast('刷新成功');
            }, 300);
        }, 1500);
    }
}

// 动态更新轮播图内容
function updateBanners() {
    const banners = [
        {
            image: '../img/banner1.jpg',
            title: '2023秋招正式启动，十大热门行业人才需求解析',
            desc: '最新行业人才需求趋势和薪资水平分析报告'
        },
        {
            image: '../img/banner2.jpg',
            title: '简历制作全攻略：HR青睐的优质简历',
            desc: '一页纸如何展现你的核心竞争力？'
        },
        {
            image: '../img/banner3.jpg',
            title: '名企校招面试技巧分享会',
            desc: '大厂HR现场分享求职面试经验'
        }
    ];
    
    // 随机打乱顺序
    const shuffledBanners = banners.sort(() => Math.random() - 0.5);
    
    // 更新DOM
    const sliderItems = document.querySelectorAll('.slider-item');
    sliderItems.forEach((item, index) => {
        if (index < shuffledBanners.length) {
            const banner = shuffledBanners[index];
            
            // 更新内容
            item.querySelector('img').src = banner.image;
            item.querySelector('h3').textContent = banner.title;
            item.querySelector('p').textContent = banner.desc;
        }
    });
}

// 动态更新文章列表
function updateArticles() {
    // 模拟新文章数据
    const articles = document.querySelector('.article-list');
    
    // 创建淡入效果
    articles.style.opacity = '0';
    
    setTimeout(() => {
        articles.style.transition = 'opacity 0.5s ease';
        articles.style.opacity = '1';
    }, 200);
    
    // 这里可以添加实际的文章数据更新逻辑
}

// 初始化搜索功能
function initSearch() {
    const searchInput = document.querySelector('.search-bar input');
    if (!searchInput) return;
    
    // 添加搜索建议容器
    const searchContainer = document.querySelector('.search-bar');
    const suggestionContainer = document.createElement('div');
    suggestionContainer.className = 'search-suggestions';
    searchContainer.appendChild(suggestionContainer);
    
    // 搜索建议数据
    const suggestions = [
        '实习机会', '简历模板', '面试技巧', '校园招聘', 
        '职业规划', '求职攻略', 'AI行业', '互联网就业',
        '大厂内推', '产品经理', '数据分析', '前端开发'
    ];
    
    // 输入事件处理
    searchInput.addEventListener('input', function() {
        const query = this.value.trim();
        
        if (query.length === 0) {
            hideSearchSuggestions();
            return;
        }
        
        // 过滤相关建议
        const filteredSuggestions = suggestions.filter(item => 
            item.toLowerCase().includes(query.toLowerCase())
        );
        
        // 显示建议
        if (filteredSuggestions.length > 0) {
            showSearchSuggestions(filteredSuggestions);
        } else {
            hideSearchSuggestions();
        }
    });
    
    // 焦点事件处理
    searchInput.addEventListener('focus', function() {
        const query = this.value.trim();
        if (query.length > 0) {
            const filteredSuggestions = suggestions.filter(item => 
                item.toLowerCase().includes(query.toLowerCase())
            );
            
            if (filteredSuggestions.length > 0) {
                showSearchSuggestions(filteredSuggestions);
            }
        } else {
            // 显示热门搜索
            showSearchSuggestions(suggestions.slice(0, 6), '热门搜索');
        }
    });
    
    // 点击页面其他地方隐藏建议
    document.addEventListener('click', function(e) {
        if (!e.target.closest('.search-bar')) {
            hideSearchSuggestions();
        }
    });
    
    // 处理搜索提交
    searchInput.addEventListener('keypress', function(e) {
        if (e.key === 'Enter') {
            const query = this.value.trim();
            if (query) {
                performSearch(query);
            }
        }
    });
    
    // 显示搜索建议
    function showSearchSuggestions(items, title = '') {
        suggestionContainer.innerHTML = '';
        
        if (title) {
            const titleElement = document.createElement('div');
            titleElement.className = 'suggestion-title';
            titleElement.textContent = title;
            suggestionContainer.appendChild(titleElement);
        }
        
        items.forEach(item => {
            const suggestion = document.createElement('div');
            suggestion.className = 'suggestion-item';
            suggestion.textContent = item;
            suggestion.addEventListener('click', () => {
                searchInput.value = item;
                performSearch(item);
            });
            suggestionContainer.appendChild(suggestion);
        });
        
        suggestionContainer.style.display = 'block';
    }
    
    // 隐藏搜索建议
    function hideSearchSuggestions() {
        suggestionContainer.style.display = 'none';
    }
    
    // 执行搜索
    function performSearch(query) {
        hideSearchSuggestions();
        showToast(`搜索: ${query}`);
        // 这里可以添加实际的搜索逻辑
        window.location.href = `search-results.html?q=${encodeURIComponent(query)}`;
    }
}

// 初始化加载更多功能
function initLoadMore() {
    // 所有需要支持加载更多的容器
    const containers = [
        {
            selector: '.article-list',
            type: 'article',
            module: 'insights'
        },
        {
            selector: '.tips-container',
            type: 'tips',
            module: 'job-tips'
        }
    ];
    
    // 添加加载更多按钮
    containers.forEach(container => {
        const element = document.querySelector(container.selector);
        if (!element) return;
        
        // 如果还没有加载更多按钮，则添加
        const moduleElement = element.closest(`.${container.module}`);
        if (moduleElement && !moduleElement.querySelector('.load-more-btn')) {
            const loadMoreContainer = document.createElement('div');
            loadMoreContainer.className = 'load-more-container';
            
            const loadMoreBtn = document.createElement('button');
            loadMoreBtn.className = 'load-more-btn';
            loadMoreBtn.innerHTML = '加载更多 <i class="bi bi-chevron-down"></i>';
            loadMoreBtn.dataset.type = container.type;
            
            loadMoreBtn.addEventListener('click', function() {
                loadMoreContent(this);
            });
            
            loadMoreContainer.appendChild(loadMoreBtn);
            moduleElement.appendChild(loadMoreContainer);
        }
    });
}

// 加载更多内容
function loadMoreContent(button) {
    // 显示加载状态
    button.innerHTML = '<i class="bi bi-arrow-repeat spin"></i> 加载中...';
    button.disabled = true;
    
    // 根据类型加载不同内容
    const type = button.dataset.type;
    
    // 模拟加载延迟
    setTimeout(() => {
        let success = false;
        
        switch(type) {
            case 'article':
                success = loadMoreArticles();
                break;
            case 'tips':
                success = loadMoreTips();
                break;
            default:
                console.error('未知的内容类型');
        }
        
        // 恢复按钮状态
        if (success) {
            button.innerHTML = '加载更多 <i class="bi bi-chevron-down"></i>';
            button.disabled = false;
        } else {
            button.innerHTML = '没有更多内容了';
            button.disabled = true;
        }
    }, 1000);
}

// 加载更多文章
function loadMoreArticles() {
    // 实现加载更多文章的逻辑
    console.log('加载更多文章');
    return true;
}

// 加载更多干货
function loadMoreTips() {
    // 实现加载更多干货的逻辑
    console.log('加载更多干货');
    return true;
}

// 初始化动画效果
function initAnimations() {
    // 添加页面元素的进入动画
    const animatedElements = document.querySelectorAll('.module, .quick-access, .banner-slider');
    
    // 使用Intersection Observer API检测元素进入视口
    const observer = new IntersectionObserver((entries) => {
        entries.forEach(entry => {
            if (entry.isIntersecting) {
                entry.target.classList.add('animate-in');
                observer.unobserve(entry.target);
            }
        });
    }, {
        threshold: 0.1
    });
    
    // 观察所有需要动画的元素
    animatedElements.forEach(element => {
        observer.observe(element);
    });
}

// 显示Toast消息
function showToast(message) {
    // 如果已有Toast，则先移除
    const existingToast = document.querySelector('.toast-message');
    if (existingToast) {
        existingToast.remove();
    }
    
    // 创建Toast元素
    const toast = document.createElement('div');
    toast.className = 'toast-message';
    toast.textContent = message;
    document.body.appendChild(toast);
    
    // 显示Toast
    setTimeout(() => {
        toast.classList.add('show');
    }, 10);
    
    // 自动消失
    setTimeout(() => {
        toast.classList.remove('show');
        setTimeout(() => {
            toast.remove();
        }, 300);
    }, 2500);
}

// 页面可见性改变时处理（切换到后台暂停自动播放，切换回来继续）
document.addEventListener('visibilitychange', function() {
    if (document.hidden) {
        // 页面不可见，可以暂停一些操作
        console.log('页面不可见，暂停自动播放');
    } else {
        // 页面可见，恢复操作
        console.log('页面可见，恢复自动播放');
        // 重新初始化轮播图
        initSlider();
    }
}); 